import router from "@/router";
import { RouteRecordRaw } from "vue-router"
import { IBreadcrumb } from "@/base-ui/breadcrumb/types"

let firstMenu: any = undefined

// 加载路由
export function menuMapToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  // 1.读取本地所有的路由
  const allRoutes: RouteRecordRaw[] = [] // 保存 本地的文件
  const routeFiles = require.context('../router/main', true, /\.ts/) // 递归查询 main 文件下的所以属于 .ts文件
  routeFiles.keys().forEach((key) => {
    const route = require("../router/main" + key.split('.')[1])
    allRoutes.push(route.default)
    // console.log(allRoutes);
  })

  // 2, 菜单映射，递归的查询
  const _recurseGetRoute = (menus: any[]) => {
    for (const item of menus) {
      if (item.type === 2) {
        const route = allRoutes.find((route) => route.path === item.url)
        if (route) routes.push(route)
        if (!firstMenu) {
          firstMenu = item
          // console.log(firstMenu);
        }
      } else {
        _recurseGetRoute(item.children ?? [])
      }
    }
  }
  _recurseGetRoute(userMenus)
  return routes
}

// 获取面包屑数据
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
  let Breadcrumbs: IBreadcrumb[] = []
  pathMapToMenu(userMenus, currentPath, Breadcrumbs)
  return Breadcrumbs
}

// 递归匹配路由
export function pathMapToMenu(userMenus: any[], currentPath: string, Breadcrumbs?: IBreadcrumb[]): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        Breadcrumbs?.push({ name: menu.name, path: menu.path ?? '/' })
        Breadcrumbs?.push({ name: findMenu.name, path: findMenu.path ?? '/' })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

// 根据菜单获取所有的按钮权限
export function menuMapToPermissions(userMenus: any[]) {
  const permissions: string[] = []

  // 递归查询
  const _recurseGetPermission = (munes: any[]) => {
    for (const menu of munes) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }

  _recurseGetPermission(userMenus)
  return permissions
}

export function menuMapLeaFKeys(menuList: any[]) {
  const leafKeys: number[] = []

  const _recurseGetChecked = (menuList: any[]) => {
    for (const item of menuList) {
      if (item.children) {
        _recurseGetChecked(item.children ?? [])
      } else {
        leafKeys.push(item.id)
      }
    }
  }

  _recurseGetChecked(menuList)

  return leafKeys

}
export { firstMenu }